//
//  CTWebViewController.m
//  iosWebViewTester
//
//  Created by 任玺 on 15/12/26.
//  Copyright © 2015年 财通证券. All rights reserved.
//

#import "CTWebViewController.h"
#import "NJKWebViewProgress.h"
#import "NJKWebViewProgressView.h"
#import "CTWebViewCommon.h"

@interface CTWebViewController () <UIGestureRecognizerDelegate, UIWebViewDelegate, NJKWebViewProgressDelegate>

@end

@implementation CTWebViewController
{
    NSURLRequest *_request;
    NSString *_title;
    BOOL _isAlwaysRefesh;
    id<CTWebViewControllerDelegate> _delegate;
    
    UIBarButtonItem *_goBackItem;
    UIBarButtonItem *_closeItem;
    
    UIWebView *_webView;
    NJKWebViewProgress *_progressProxy;
    NJKWebViewProgressView *_progressView;
    
    UILabel *_noticeLabel;
    UIActivityIndicatorView *_activityIndicatorView;    //用于等待内容加载
}

/**
 *  用url初始化 webView Controller
 *
 *  @param NSURLRequest
 *  @param isAlwaysRefesh 总是当前界面刷新
 *  @param <CTWebViewControllerDelegate> 委托
 */
-(instancetype)initWithUrlRequest:(NSURLRequest *)request
                     title:(NSString *)title
            isAlwaysRefesh:(BOOL)isAlwaysRefesh
                  delegate:(id<CTWebViewControllerDelegate>)delegate
{
    if(self = [super init]){
        _request = request;
        _title = title;
        _isAlwaysRefesh = isAlwaysRefesh;
        _delegate = delegate;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    //self.view.backgroundColor = [UIColor whiteColor];

    if(_title.length){
        self.navigationItem.title = _title;
    }
    
    /**
     *  禁止菜单弹出
     */
    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setMenuVisible:NO animated:YES];
    
    if (_isAlwaysRefesh) {
        UIButton *goBackBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
        [goBackBtn setImage:[UIImage imageNamed:@"nav_bar_back"] forState:UIControlStateNormal];
        [goBackBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 40)];
        [goBackBtn setTitle:@"返回" forState:UIControlStateNormal];
        [goBackBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [goBackBtn setTitleColor:[[UIColor whiteColor] colorWithAlphaComponent:0.4] forState:UIControlStateHighlighted];
        goBackBtn.titleLabel.font = FONT_SYSTEM_RESIZED(16);
        [goBackBtn addTarget:self action:@selector(goBackBtnAction) forControlEvents:UIControlEventTouchUpInside];
        _goBackItem = [[UIBarButtonItem alloc] initWithCustomView:goBackBtn];
        
        UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 36, 44)];
        [closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
        closeBtn.titleLabel.font = FONT_SYSTEM_RESIZED(16);
        [closeBtn setTitleColor:[[UIColor whiteColor] colorWithAlphaComponent:0.4] forState:UIControlStateHighlighted];
        [closeBtn addTarget:self action:@selector(closeBtnAction) forControlEvents:UIControlEventTouchUpInside];
        _closeItem = [[UIBarButtonItem alloc] initWithCustomView:closeBtn];
        
        UIBarButtonItem *spacerItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                    target:nil
                                                                                    action:nil];
        spacerItem.width = -10;
        self.navigationItem.leftBarButtonItems = @[spacerItem, _goBackItem, _closeItem];
    }
    
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_HEIGHT)];
    _webView.scalesPageToFit = NO;
    _webView.scrollView.bounces = NO;
    _webView.dataDetectorTypes = UIDataDetectorTypeNone;
    _webView.delegate = self;
    _webView.allowsInlineMediaPlayback = YES;
    [self.view addSubview:_webView];
    
    [_webView loadRequest:_request];
    
    if (self.navigationController.viewControllers.count >1) {
        UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureAction:)];
        panGestureRecognizer.delegate = self;
        [self.view addGestureRecognizer:panGestureRecognizer];
    }
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.modalPresentationCapturesStatusBarAppearance = NO;
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    [backItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:FONT_SYSTEM(16.0f)} forState:UIControlStateNormal];
    self.navigationItem.backBarButtonItem = backItem;
    self.navigationItem.backBarButtonItem.title = @"";
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    //self.navigationController.navigationBarHidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (BOOL)prefersStatusBarHidden
{
    return NO; // 是否隐藏状态栏
}

#pragma mark - Navgition Btn Action
-(void)leftBtnPressed
{
    
}

-(void)rightBtnPressed
{
    
}

-(void)goBackBtnAction
{
    if(_isAlwaysRefesh && [_webView canGoBack]){
        [_webView goBack];
        
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)closeBtnAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    CGPoint touchPoint = [gestureRecognizer locationInView:self.view];
    CGPoint translationPoint = [(UIPanGestureRecognizer *)gestureRecognizer translationInView:self.view];
    
    if (CGRectGetMinX(self.view.frame) == 0
        && translationPoint.x>0 //右侧滑动
        && touchPoint.x < SCREEN_WIDTH/5){
        return YES;
        
    }else {
        return NO;
    }
}

#pragma mark - UIGestureRecognizer Action
-(void)panGestureAction:(UIPanGestureRecognizer *)panGestureRecognizer
{
    switch (panGestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
        
            break;
            
        case UIGestureRecognizerStateChanged:{
            
            //当前滑动到的X
            CGFloat changedX = [panGestureRecognizer locationInView:self.view].x;
            if(changedX>SCREEN_WIDTH/5){
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
            break;
            
        default:
            break;
    }

}

#pragma mark - NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"%@", request.URL);
    
    NSRange range = [request.URL.absoluteString rangeOfString:@".html"];
    
    if (![request.URL.absoluteString isEqualToString:_request.URL.absoluteString]
        && range.location != NSNotFound) {
        
        CTWebViewController *webViewController = [[CTWebViewController alloc] initWithUrlRequest:request
                                                                                           title:_title
                                                                                  isAlwaysRefesh:NO
                                                                                        delegate:nil];
        [self.navigationController pushViewController:webViewController animated:YES];
        
        return NO;
        
    }else{
        return YES;
    }

    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if ([error code] == NSURLErrorCancelled){
        NSLog(@"Canceled request: %@", [webView.request.URL absoluteString]);
        return;
    }
    
    [_activityIndicatorView stopAnimating];
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"页面加载有错误"
                                                        message:error.localizedDescription
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
    [alertView show];
}

#pragma mark - Web Call Native
/**
 *  隐藏title接口, url方式、还有重定向方式
 */
-(void)hideTopBar
{
    if (_delegate
        && [_delegate conformsToProtocol:@protocol(CTWebViewControllerDelegate)]
        && [_delegate respondsToSelector:@selector(hideTopBar)]) {
        [_delegate hideTopBar];
    }
}

/**
 *  设置右上角按钮
 */
-(void)setRightButton
{
    if (_delegate
        && [_delegate conformsToProtocol:@protocol(CTWebViewControllerDelegate)]
        && [_delegate respondsToSelector:@selector(setRightButton)]) {
        [_delegate setRightButton];
    }
}

@end
